package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.User;
import cn.huhst.cas.weisiqian.service.UserService;
import cn.huhst.cas.weisiqian.util.JSON;
import cn.huhst.cas.weisiqian.util.Utils;

@WebServlet(urlPatterns = { "/ChangePassword.do" })
public class ChangePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userservice = null;
	private Logger logger = Logger.getLogger(ChangePassword.class);

	public ChangePassword() {
		super();
		userservice = new UserService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String oldpassword = request.getParameter("oldpassword");
		String password = request.getParameter("password");
		String passwordconf = request.getParameter("passwordconf");
		logger.info("username=" + username + " oldpassword=" + oldpassword + " password=" + password + " passwordconf="
				+ passwordconf);
		User user = userservice.isExistNameAndPassword(username, Utils.encry(oldpassword));
		JSON json = new JSON();

		if(!oldpassword.matches(User.userpasswordRegx)){
			json.put("oldpassword", "密码不少于6个词字符但不多于22个词字符(词字符：大小写字母和数字)");
		}
		json = User.checkUserPasswordFormat(password, json);
		if(!passwordconf.matches(User.userpasswordRegx)){
			json.put("passwordconf", "密码不少于6个词字符但不多于22个词字符(词字符：大小写字母和数字)");
		}

		if (json.isEmpty()) {
			if (user != null) {
				if(password.equals(passwordconf)){
					user.setUserpassword(Utils.encry(password));
					boolean result = userservice.updateUser(user);
					if(result){
						logger.info("修改密码成功");
						json.putOKMSG("修改密码成功");
					}else{
						logger.error("修改密码失败");
						json.putErrorMSG("修改密码失败");
					}
				}else{
					logger.error("两次密码不一致");
					json.putErrorMSG("两次密码不一致");
				}
			} else {
				logger.error("旧密码错误");
				json.putErrorMSG("旧密码错误");
			}
		} else {
			logger.error("json:" + json);
			json.putErrorMSG("用户信息格式有误");
		}
		
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
	}

}
